
// store error strings in flash to save RAM
#define error(s, i) error_P(PSTR(s), i)



void appendToFile(char* fileName, String txt)
{
    SdCard card;
    // initialize the SD card
    if (!card.init())
      error("card.init", card.errorCode);
  
    // initialize a FAT16 volume
    if (!Fat16::init(&card))
      error("Fat16::init", card.errorCode);
  
    Fat16 file;
    // clear write error
    file.writeError = false;
  
    // O_CREAT - create the file if it does not exist
    // O_APPEND - seek to the end of the file prior to each write
    // O_WRITE - open for write
    if (!file.open(fileName, O_CREAT | O_APPEND | O_WRITE))
        error("error opening file", card.errorCode);
    
    file.print(txt);

    if (!file.close()) 
        error("error closing file", card.errorCode);
}

void error_P(const char* str, int cardErrorCode)
{
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (cardErrorCode)
  {
    PgmPrint("SD error: ");
    Serial.println(cardErrorCode, HEX);
  }
  while(1);
}

